package com.lqkj.officialweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lqkj.officialweb.po.TNewsBanner;
import com.lqkj.officialweb.service.NewsBannerService;
import com.lqkj.officialweb.utils.BaiDuHotUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author Linm
 */
@RestController
@RequestMapping("newsBanner")
public class NewsBannerController extends ApiController {

   // public static final String BAIDU_URL = "https://api.1314.cool/getbaiduhot/";
    /**
     * 百度热搜接口不能使用，更换热搜接口
     *
     * 在HOTLIST_URL接口的链接中更换不同的type参数，即可更换不同的热搜榜，例：“type=juejin”即掘金热榜
     * type参数值	说明
     * zhihu	    知乎热榜
     * weibo	    微博热搜
     * weixin	    微信 ‧ 24h热文榜
     * baidu	    百度 ‧ 实时热点
     * toutiao	    今日头条
     * 163	        网易新闻
     * xl	        新浪网 ‧ 热词排行榜
     * 36k      	36氪 ‧ 24小时热榜(默认)
     * hitory	    历史上的今天
     * sspai	    少数派
     * csdn     	**csdn **今日推荐
     * juejin	    掘金热榜
     * bilibili     哔哩哔哩热榜
     * douyin	    抖音视频榜
     * 52pojie	    吾爱破解热榜
     * v2ex	        V2ex 热帖
     * hostloc	    全球主机论坛热帖
     */
    public static  final String HOTLIST_URL= "https://v2.alapi.cn/api/tophub/get?type=juejin&token=Eo5Je0AJi3RxiIOZ";

    /**
     * 服务对象
     */
    @Resource
    private NewsBannerService newsBannerService;


    /**
     * 核心业务内容分页查询（单表查询）
     *
     * @param page
     * @param searchModel
     * @return
     */
    @GetMapping("list")
    public R selectList(TNewsBanner searchModel, Page<Map<String, Object>> page) {
        return success(newsBannerService.getList(page, searchModel));
    }


    /**
     * 分页查询所有数据
     *
     * @param page        分页对象CoreBusinessDao
     * @param tNewsBanner 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<TNewsBanner> page, TNewsBanner tNewsBanner) {
        return success(this.newsBannerService.page(page, new QueryWrapper<>(tNewsBanner)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.newsBannerService.getById(id));
    }

    /*
     * 新增数据
     *
     * @param product 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody TNewsBanner tNewsBanner) {
        boolean rs = this.newsBannerService.save(tNewsBanner);
        return success(rs ? tNewsBanner : null);
    }

    /**
     * 修改数据
     *
     * @param tNewsBanner 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody TNewsBanner tNewsBanner) {
        boolean rs = this.newsBannerService.updateById(tNewsBanner);
        return success(rs ? tNewsBanner : null);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<String> idList) {
        return success(this.newsBannerService.removeByIds(idList));
    }

    /**
     * 获取热搜榜01
     *
     * @return  热搜内容字符串返回
     */
    @GetMapping("/request")
    public @ResponseBody
    R request() {
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(HOTLIST_URL);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            return R.ok(sbf.toString());
        } catch (Exception e) {
            logger.error("/newsBanner/request is error" + e.getMessage());
            return R.failed("获取热榜异常");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取热搜榜02
     * @return  热搜内容json体返回
     * 接口/request和接口/findKnow功能一致，只不过/request返回的是字符串类型的数据，本接口返回的是json类型数据
     */
    @GetMapping("/findKnow")
    public @ResponseBody
    R findKnow() {
        BaiDuHotUtil api = new BaiDuHotUtil();
        try {
            String run = api.run(HOTLIST_URL);
            JSONObject object = JSON.parseObject(run, JSONObject.class);
            return R.ok(object);
        } catch (Exception e) {
            logger.error("/newsBanner/request is error" + e.getMessage());
            return R.failed("获取热榜异常");
        }
    }

}
